import { _decorator, Color, Component, instantiate, Label, math, Node, Prefab, resources, sp, Sprite, SpriteFrame, Tween, tween, v3 } from 'cc';
import { StartSceneGameMgr } from './StartSceneGameMgr';
import { UserInfo } from './UserInfo';
import { roleEquipEnum } from '../Enum';
import { LayerBase } from './LayerBase';
import { UILayerMgr } from './UILayerMgr';
import { EquipCellItem } from './EquipCellItem';
import { convertNumber, keepOneDecimalFull2, keepOneDecimalFullFomatFloat } from '../utils/utils';
import { RoleCellItem } from './RoleCellItem';
import { loading } from '../loading';
import { Start } from './Start';
import { RoleChipCellItem } from './RoleChipCellItem';
import { AudioMgr } from '../utils/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('EquipPanel')
export class EquipPanel extends LayerBase {

    @property(Node)
    TopRoot: Node = null
    @property(Node)
    rolesp: Node = null;
    @property(Label)
    roleNameLabel: Label = null
    @property(Label)
    battleValueLabel: Label = null
    @property(Label)
    attackAttributeLabel: Label = null
    @property(Label)
    frequencyContentAttributeLabel: Label = null
    @property(Label)
    criticalHitContentAttributeLabel: Label = null
    @property(Node)
    equipHouseRootContent: Node = null
    @property(Node)
    selfEquipRoot: Node = null
    @property(Node)
    roleRootContent: Node = null
    @property(Node)
    roleChipRootContent: Node = null
    @property(Prefab)
    roleCellPre: Prefab = null;
    @property(Prefab)
    roleChipCellPre: Prefab = null;
    @property(Prefab)
    equipCellPre: Prefab = null;
    @property(Node)
    roleClassBottomToogleRootContent: Node;
    @property(Node)
    equipClassBottomToogleRootContent: Node;
    @property(Node)
    isGoBattleBtn: Node
    @property(Node)
    alreadyGoBattleNode: Node;
    @property(Node)
    isNotHasNode: Node;
    @property(Node)
    currSelectPetSp:Node;
    @property(Node)
    chipRoleScrollView:Node;
    @property(Node)
    hasRoleScrollView:Node;
    @property(Node)
    roleSelectBtn0:Node;
    @property(Node)
    roleSelectBtn1:Node;
    @property(Node)
    compositionBtn:Node;
    @property(Node)
    salvageBtn:Node;
    
    
    selectRoleClassIndex: number = -1;
    selectEquipClassIndex: number = -1;
    selectHasRoleOrChipRole:number=0;


    protected onLoad(): void {

    }

    init(somedData = null) {
        this.rolesp.active = false
        let selectRoleTp = UserInfo.roleCongfiDic.get(StartSceneGameMgr.ins.roleSelectId);

         //更新上阵宠物
         let goBattlePet = StartSceneGameMgr.ins.getGoBattlePet();
 
         if (goBattlePet) {
            console.log("有上阵宠物")

           this.currSelectPetSp.active = true;
           resources.load(`${goBattlePet.petTp.imgPath}/spriteFrame`,SpriteFrame,(err,res)=>{
             this.currSelectPetSp.getComponent(Sprite).spriteFrame=res;
           })
             
           tween(this.currSelectPetSp)
           .tag(46)
           .to(0.4,{scale:v3(1,1.1,1),position:v3(0,30,0)})
           .to(0.4,{scale:v3(1,1,1),position:v3(0,0,0)})
           .union()
           .repeatForever()
           .start()
         }
         else{
            console.log("没有上阵宠物")
             this.currSelectPetSp.active = false;
         }

        //更新ui
        this.TopRoot.getChildByName("crystalRoot").getChildByName("value").getComponent(Label).string = convertNumber(UserInfo.crystalMun);
        this.TopRoot.getChildByName("coinRoot").getChildByName("value").getComponent(Label).string = convertNumber(UserInfo.coinMun);

        //更新角色仓库显示是碎片还是已拥有
        if (this.selectHasRoleOrChipRole==0) {
            this.hasRoleScrollView.active=true;
            this.chipRoleScrollView.active=false;
            this.roleSelectBtn0.getChildByName("selectNode").active=true;
            this.roleSelectBtn1.getChildByName("selectNode").active=false;
        }
        else{
            this.hasRoleScrollView.active=false;
            this.chipRoleScrollView.active=true;
            this.roleSelectBtn0.getChildByName("selectNode").active=false;
            this.roleSelectBtn1.getChildByName("selectNode").active=true;
        }

        //更新装备仓库
        this.equipHouseRootContent.removeAllChildren();
        this.selfEquipRoot.children[0].getChildByName("content").removeAllChildren();
        this.selfEquipRoot.children[1].getChildByName("content").removeAllChildren();
        this.selfEquipRoot.children[2].getChildByName("content").removeAllChildren();
        UserInfo.hasEquipDic.getValueList().forEach((ele) => {
            if (ele.ownerRoleId == -1) {
                if (this.selectEquipClassIndex == -1) {//如果是所有分类
                    let pre = instantiate(this.equipCellPre);
                    pre.setParent(this.equipHouseRootContent);
                    pre.getComponent(EquipCellItem).init(ele);
                }
                else {
                    if (ele.equipTp.quality == this.selectEquipClassIndex) {
                        let pre = instantiate(this.equipCellPre);
                        pre.setParent(this.equipHouseRootContent);
                        pre.getComponent(EquipCellItem).init(ele);
                    }
                }
            }
        })

        //角色仓库,已拥有
        this.roleRootContent.removeAllChildren();
        UserInfo.hasRoleDic.getValueList().forEach(element => {
            if (this.selectRoleClassIndex == -1) {//如果是所有分类
                let pre = instantiate(this.roleCellPre);
                pre.setParent(this.roleRootContent);
                pre.getComponent(RoleCellItem).init(element);
            }
            else {
                if (element.roleTp.quality == this.selectRoleClassIndex) {
                    let pre = instantiate(this.roleCellPre);
                    pre.setParent(this.roleRootContent);
                    pre.getComponent(RoleCellItem).init(element);
                }
            }
        });

        //角色仓库,未拥有
        this.roleRootContent.removeAllChildren();
        UserInfo.hasRoleDic.getValueList().forEach(element => {
            if (this.selectRoleClassIndex == -1) {//如果是所有分类
                let pre = instantiate(this.roleCellPre);
                pre.setParent(this.roleRootContent);
                pre.getComponent(RoleCellItem).init(element);
            }
            else {
                if (element.roleTp.quality == this.selectRoleClassIndex) {
                    let pre = instantiate(this.roleCellPre);
                    pre.setParent(this.roleRootContent);
                    pre.getComponent(RoleCellItem).init(element);
                }
            }
        });

         //角色仓库,碎片
         this.roleChipRootContent.removeAllChildren();
         UserInfo.roleCongfiDic.getValueList().forEach(element => {
             if (this.selectRoleClassIndex == -1) {//如果是所有分类
                 let pre = instantiate(this.roleChipCellPre);
                 pre.setParent(this.roleChipRootContent);
                 pre.getComponent(RoleChipCellItem).init(element);
             }
             else {
                 if (element.quality == this.selectRoleClassIndex) {
                     let pre = instantiate(this.roleChipCellPre);
                     pre.setParent(this.roleChipRootContent);
                     pre.getComponent(RoleChipCellItem).init(element);
                 }
             }
         });

        //更新底部分类ui
        for (let i = 0; i < this.roleClassBottomToogleRootContent.getChildByName("bg").children.length; i++) {
            this.roleClassBottomToogleRootContent.getChildByName("bg").children[i].getComponent(Label).color = new Color().fromHEX("#B88181")
        }
        this.roleClassBottomToogleRootContent.getChildByName("bg").children[this.selectRoleClassIndex + 1].getComponent(Label).color = new Color().fromHEX("#FFFFFF");

        for (let i = 0; i < this.equipClassBottomToogleRootContent.getChildByName("bg").children.length; i++) {
            this.equipClassBottomToogleRootContent.getChildByName("bg").children[i].getComponent(Label).color = new Color().fromHEX("#555555")
        }
        this.equipClassBottomToogleRootContent.getChildByName("bg").children[this.selectEquipClassIndex + 1].getComponent(Label).color = new Color().fromHEX("#FFFFFF");

         //更新是否显示可合成按钮
         if(StartSceneGameMgr.ins.roleSelectId>=0){
            this.compositionBtn.active=false;

         }
         else{
            if (UserInfo.hasRoleChipArr[-StartSceneGameMgr.ins.roleSelectId]>=UserInfo.roleCongfiDic.get(-StartSceneGameMgr.ins.roleSelectId).totalChipNum) {
                this.compositionBtn.active=true;
            }
            else{
            this.compositionBtn.active=false;
            }
         }

        //更新是否显示分解按钮
        if (StartSceneGameMgr.ins.roleSelectId >= 0) {
            this.salvageBtn.active = true;

            if (UserInfo.hasRoleDic.lenght <= 1) {//如果只有一个角色了不能分解
                this.salvageBtn.active = false;
            }
        }
        else {
            this.salvageBtn.active = false;
        }

        if (StartSceneGameMgr.ins.roleSelectId>=0) {//选择的是拥有的角色item
            let role = UserInfo.hasRoleDic.get(StartSceneGameMgr.ins.roleSelectId);
            this.roleNameLabel.string = role.roleTp.name;
            this.isNotHasNode.active = false;
            console.log(role.roleTp.roleId,"role.roleTp.roleId")
            console.log(UserInfo.currGoBattleRoleId,"UserInfo.currGoBattleRoleId")
            if (role.roleId == UserInfo.currGoBattleRoleId) {
                console.log("他上阵了")
                this.alreadyGoBattleNode.active = true;
                this.isGoBattleBtn.active = false;
            }
            else {
                console.log("他没阵了")

                this.alreadyGoBattleNode.active = false;
                this.isGoBattleBtn.active = true;
            }

            const obj = {
                n: 0
            }
            tween(obj)
                .tag(11)

                .to(2, { n: role.battleValue }, {
                    onUpdate: (target, ratio) => {
                        this.battleValueLabel.string = Math.round(obj.n) + ""
                    }
                })
                .start()

            const obj1 = {
                n: 0
            }
            tween(obj1)
                .tag(11)

                .to(1, { n: role.roleAttackAttribute }, {
                    onUpdate: (target, ratio) => {
                        this.attackAttributeLabel.string = Math.round(obj1.n) + ""
                    }
                })
                .start()

            const obj2 = {
                n: 0
            }
            tween(obj2)
                .tag(11)

                .to(1, { n: role.roleFrequencyAttribute }, {
                    onUpdate: (target, ratio) => {
                        this.frequencyContentAttributeLabel.string = keepOneDecimalFullFomatFloat(obj2.n, 2)
                    }
                })
                .start()

            const obj3 = {
                n: 0
            }
            tween(obj3)
                .tag(11)
                .to(1, { n: role.roleCriticalHitAttribute * 100 }, {
                    onUpdate: (target, ratio) => {
                        this.criticalHitContentAttributeLabel.string = keepOneDecimalFullFomatFloat(obj3.n, 1) + "%"
                    }
                })
                .start()

            //更新拥有角色
            resources.loadDir(`${role.roleTp.spinePath}`, sp.SkeletonData, (err, data) => {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let comp = this.rolesp.getComponent(sp.Skeleton);
                    comp.skeletonData = data[0];
                    comp.setAnimation(0, "Standby", true);

                }
            })
            this.rolesp.getComponent(sp.Skeleton).color=Color.WHITE;
            if (role.roleType == 5) {
                this.rolesp.scale = v3(0.2, 0.2, 1)
            }
            else {
                this.rolesp.scale = v3(1, 1, 1)
            }

            //更新角色已经装备槽
            this.selfEquipRoot.children[0].getChildByName("lockIcon").active = false;
            this.selfEquipRoot.children[1].getChildByName("lockIcon").active = false;
            this.selfEquipRoot.children[2].getChildByName("lockIcon").active = false;
            role.getSelfAllEquipDic().getValueList().forEach((element) => {
                let pre = instantiate(this.equipCellPre);
                pre.setParent(this.selfEquipRoot.children[element.equipTp.equipClass].getChildByName("content"));
                pre.getComponent(EquipCellItem).init(element, false);
            });
        }
        else {//选择的是未拥有的角色碎片item
            let roleCongfi = UserInfo.roleCongfiDic.get(-StartSceneGameMgr.ins.roleSelectId);
            this.roleNameLabel.string = roleCongfi.name;
            this.alreadyGoBattleNode.active = false
            this.isGoBattleBtn.active = false;
            this.isNotHasNode.active = true;

            Tween.stopAllByTag(11);
            this.battleValueLabel.string = "???"
            this.attackAttributeLabel.string = "???"
            this.frequencyContentAttributeLabel.string = "???"
            this.criticalHitContentAttributeLabel.string = "???"

            //更新拥有角色
            resources.loadDir(`${roleCongfi.spinePath}`, sp.SkeletonData, (err, data) => {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let comp = this.rolesp.getComponent(sp.Skeleton);
                    comp.skeletonData = data[0];
                    comp.setAnimation(0, "Standby", true);

                }
            })
            this.rolesp.getComponent(sp.Skeleton).color=new Color().fromHEX("#202020");
            if (roleCongfi.roleType == 5) {
                this.rolesp.scale = v3(0.2, 0.2, 1)
            }
            else {
                this.rolesp.scale = v3(1, 1, 1)
            }

            //更新角色已经装备槽
            this.selfEquipRoot.children[0].getChildByName("lockIcon").active = true;
            this.selfEquipRoot.children[1].getChildByName("lockIcon").active = true;
            this.selfEquipRoot.children[2].getChildByName("lockIcon").active = true;

           
        }

        setTimeout(() => {
            this.rolesp.active = true
        }, 100);

    }

    onclickRoleClassBottomToggleBtn(event, index) {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        this.selectRoleClassIndex = parseInt(index);
        this.init();
    }

    onclickEquipClassBottomToggleBtn(event, index) {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        this.selectEquipClassIndex = parseInt(index);
        this.init();
    }

    onclickCrystalAddBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        UILayerMgr.getIns.openUILayer("getCoinCrystalPanel");
    }

    onclickIsGoBattleBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        UserInfo.currGoBattleRoleId = StartSceneGameMgr.ins.roleSelectId;
        StartSceneGameMgr.ins.saveGameDate();
        UILayerMgr.getIns.resfreshUI(this.node.name);
        Start.ins.initHomePanel();
    }

    onclickSelectHasRoleOrChipRoleBtn(event, index) {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        if (this.selectHasRoleOrChipRole == index) {
            return;
        }
        switch (index) {
            case "0":
                this.selectHasRoleOrChipRole = 0;
                StartSceneGameMgr.ins.roleSelectId=UserInfo.currGoBattleRoleId;
                UILayerMgr.getIns.resfreshUI(this.node.name);
                break;
            case "1":
                this.selectHasRoleOrChipRole = 1;
                StartSceneGameMgr.ins.roleSelectId=-1;
                UILayerMgr.getIns.resfreshUI(this.node.name);
                break;
        }

    }

    //点击合成按钮
    onclickCompositionBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn",0.8);

        let _roleType=-StartSceneGameMgr.ins.roleSelectId;
        UserInfo.hasRoleChipArr[_roleType]-=UserInfo.roleCongfiDic.get(_roleType).totalChipNum;
        StartSceneGameMgr.ins.getRole(_roleType);
        let rewardCongfi = UserInfo.roleCongfiDic.get(_roleType)
        rewardCongfi.count = 1;
        UILayerMgr.getIns.openUILayer("getRewardPanel", rewardCongfi);

        UILayerMgr.getIns.resfreshUI(this.node.name);
        StartSceneGameMgr.ins.saveGameDate();
    }

    //点击分解按钮
    onclickSalvageBtn() {
        AudioMgr.ins.playOneShot("audio/clickSalvageBtn",0.8);

        UILayerMgr.getIns.openUILayer("salvageRolePanel",UserInfo.hasRoleDic.get(StartSceneGameMgr.ins.roleSelectId))
    }




}


